import { ParamsNotValidError, CustomerError, NotFoundError, NotPermitError } from "@jingli/error";
import { DB } from '../model';

export async function authenticate(req, res, next) {
    if (/^\/auth\//.test(req.url) && !/^\/auth\/pong/.test(req.url)) { 
        return next();
    }
    
    try {
        let { token } = req.headers;
        if (!token) { 
            throw new CustomerError(403, '登录已失效');
        }
        let m = await DB.models['Token'].findOne({ where: { token: token } });
        if (!m || !m.uid) {
            throw new CustomerError(403, '登录已失效');
        }
        let user = await DB.models['User'].findById(m.uid);
        if (!user) {
            throw new CustomerError(403, '登录已失效');
        }
        if (!req.session) {
            req.session = {};
        }
        req.session.uid = user.id;
        next();
    } catch (err) {
        next(err);
    }
}